package lock;

/**
 * @author yyh
 * @create 2020-11-09 16:00
 *
 *   虚假唤醒
 */
public class ProduceAndConsumer {

    public static void main(String[] args) {

        Data data = new Data();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try{
                    data.increment();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try{
                    data.decrement();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try{
                    data.increment();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try{
                    data.decrement();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        },"D").start();

    }

    public static class Data{

        private int num = 0;

        public synchronized void increment() throws Exception{
            if(num != 0){
                this.wait();
            }
            num++;
            System.out.println(Thread.currentThread().getName() +"--->"+num);
            this.notifyAll();
        }

        public synchronized void decrement() throws Exception{
            if(num == 0){
                this.wait();
            }
            num--;
            System.out.println(Thread.currentThread().getName() +"--->"+num);
            this.notifyAll();
        }
    }
}
